package controller

import (
	"Nacos_GateWay/config"
	"Nacos_GateWay/logcat"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strconv"
	"strings"
)

func ReverseProxy(c *gin.Context) {
	for _, v := range config.Routes().Gates {
		if strings.Contains(c.Request.URL.Path, v.Url) {
			proxyUrl := strings.Replace(c.Request.URL.Path, v.Url, "", -1)
			//转发的url，端口
			target := v.Ip + ":" + strconv.FormatUint(v.Port, 10)
			u := &url.URL{}
			//转发的协议，如果是https，写https.
			u.Scheme = "http"
			u.Host = target
			proxy := httputil.NewSingleHostReverseProxy(u)

			//重写出错回调
			proxy.ErrorHandler = func(rw http.ResponseWriter, req *http.Request, err error) {
				logcat.Instance().Info("http: proxy error: %v", err)
				ret := fmt.Sprintf("http proxy error %v", err)

				//写到body里
				rw.Write([]byte(ret))
			}
			c.Request.URL.Path = proxyUrl
			proxy.ServeHTTP(c.Writer, c.Request)
			break
		}
	}

}
